package com.thread.prodcustrom;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 使用管道实现生产者消费者模型
 * @author ZGJ
 * @date 2017年6月30日
 */
public class TestPipedProduceAndCustromer {
    final PipedInputStream pis = new PipedInputStream();
    final PipedOutputStream pos = new PipedOutputStream();
    {


        try {
            pis.connect(pos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    class Producer implements Runnable {
        @Override
        public void run() {
            try {
                while(true) {
                    Thread.sleep(1000);
                    for(int i=1;i<11;i++){
	                    System.out.println(Thread.currentThread().getName() + "生产者生产了一个数字，该数字为： " + i);
	                    pos.write(i);
	                    pos.flush();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    pos.close();
                    pis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class Consumer implements Runnable {
        @Override
        public void run() {
            try {
                while(true) {
                    Thread.sleep(1000);
                    for(int i=1;i<11;i++){
	                    int num = pis.read();
	                    System.out.println("消费者消费了一个数字，该数字为：" + num);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    pos.close();
                    pis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        TestPipedProduceAndCustromer test5 = new TestPipedProduceAndCustromer();
        new Thread(test5.new Producer()).start();
        new Thread(test5.new Consumer()).start();
    }
}